import pygame, random, sys
from pygame.locals import *

import classes
import functions


WHITE = (255, 255, 255)
YELLOW = (204, 204, 0)
DARKBLUE = (0, 0, 139)
RED = (255, 0, 0)
DARKGREEN = (0, 136, 0)
GREEN = (0, 255, 0)
STORECOLOUR = (85, 102, 51)
MAXDERRICK = 8


class earthcity:
	def __init__(self, screen, scalegfx, locationinfo, proditems):
		self.thisLocation = 'earthcity'
		self.screen = screen
		self.scalegfx = scalegfx
		self.newsubcreen = False
		self.showstoreItems = False
		self.font = pygame.font.SysFont(None, 12 * self.scalegfx)
		self.researchfont = pygame.font.SysFont(None, 13 * self.scalegfx)
		self.derricks = 1
		self.displayItemInventory = False
		self.storeSelectedItem = False
		self.researchSelectedItem = False
		self.mehfuel = False
		self.interactiveIcons = []

		self.shuttleEnabled = False
		self.newshuttle = False
		self.shuttle = classes.Shuttle(self.screen, self.scalegfx, self.thisLocation, 'dockedground')
		self.shuttleManage = 'cockpit'

		self.RawMaterials = []
		self.RawMaterials = locationinfo.GetResources(self.thisLocation)
		self.RawMaterialsInventory = classes.RawMaterialsInventory()
		self.RawMaterialsInventory.InitMining(self.RawMaterials)

		self.ItemsInventory = classes.ItemInventory(proditems)
		self.StorageButtons = classes.ShowItemButtons(self.screen, self.scalegfx, 'storeselect')

		self.ResearchQueue = []
		self.ResearchButtons = classes.ShowItemButtons(self.screen, self.scalegfx, 'research')

		self.productionQueue = []
		self.productShortageList = []
		self.prodProgressList = []
		self.prodButtons = classes.ShowItemButtons(self.screen, self.scalegfx)

		self.shuttlebays = []
		self.shuttlebays.append('shuttle1')
		self.shuttlebays.append('shuttle2')
		self.shuttlebays.append('shuttle3')
		self.shuttlebays.append('shuttle4')

		self.EarthCityMainDict = functions.scaled_image_dict('main', '', '', 'gfx/EarthCityBackground.png', self.scalegfx, 48, 20)
		self.EarthCityModulesDict = functions.scaled_image_dict('earthmodules', '', '', 'gfx/earthcitymodules.png', self.scalegfx, 0, 106)
		self.EarthCityProdDict = functions.scaled_image_dict('prodbackground', '', '', 'gfx/ProductionBackground.png', self.scalegfx, 48, 20)
		self.EarthCityTrainingDict = functions.scaled_image_dict('trainingbackground', '', '', 'gfx/TrainingBackground.png', self.scalegfx, 48, 20)
		self.EarthCityResearchDict = functions.scaled_image_dict('researchbackground', '', '', 'gfx/ResearchBackground.png', self.scalegfx, 48, 20)
		self.EarthCityShuttleBayDict = functions.scaled_image_dict('shuttlebaybackground', '', '', 'gfx/ShuttleBayBackground.png', self.scalegfx, 48, 20)
		self.EarthCityMiningDict = functions.scaled_image_dict('miningbackground', '', '', 'gfx/MiningBackground.png', self.scalegfx, 48, 20)
		self.EarthCityStorageDict = functions.scaled_image_dict('storagebackground', '', '', 'gfx/StorageBackground.png', self.scalegfx, 48, 20)
	
		self.ProductionDict = functions.scaled_image_dict('production', 'Production', 'subscreen', 'gfx/Production.png', self.scalegfx, 1, 107)
		self.TrainingDict = functions.scaled_image_dict('training', 'Training', 'subscreen', 'gfx/Training.png', self.scalegfx, 1, 164)
		self.ResearchDict = functions.scaled_image_dict('research', 'Research', 'subscreen', 'gfx/Research.png', self.scalegfx, 25, 164)
		self.ShuttleBayDict = functions.scaled_image_dict('shuttlebay', 'Shuttle Bay', 'subscreen', 'gfx/ShuttleBay.png', self.scalegfx, 1, 184)
		self.MiningDict = functions.scaled_image_dict('mining', 'Mining', 'subscreen', 'gfx/Mining.png', self.scalegfx, 25, 184)
		self.StorageDict = functions.scaled_image_dict('storage', 'Stores', 'subscreen', 'gfx/Storage.png', self.scalegfx, 25, 203)
		self.ShuttleDict = functions.scaled_image_dict('shuttle', 'Earth Shuttle', 'subscreen', 'gfx/Shuttle.png', self.scalegfx, 1, 144)

		self.NoProdDict = functions.scaled_image_dict('', '', '', 'gfx/NoProd.png', self.scalegfx, 63, 52)
		self.ProdGreenLightDict = functions.scaled_image_dict('', '', '', 'gfx/ProdGreenLight.png', self.scalegfx, 303, 174)
		self.ProdCrewToBayDict = functions.scaled_image_dict('prodTeamToBay', 'Send To Bay', 'prodTeamToBay', 'gfx/ProdCrewToBay.png', self.scalegfx, 167, 195)
		self.ProdRedLightDict = functions.scaled_image_dict('', '', '', 'gfx/ProdRedLightBLitStrip.png', self.scalegfx, 313, 179)
		self.ProdRedLightAnimate = classes.animate_this(self.screen, self.ProdRedLightDict['surface'], (self.ProdRedLightDict['rect'].width / 14), self.ProdRedLightDict['rect'].height, (303*self.scalegfx), (174*self.scalegfx), 50)
		self.AugerBlitStripDict = functions.scaled_image_dict('', '', '', 'gfx/AugerBlitStrip.png', self.scalegfx, 0, 0)
		self.AugerAnimate = classes.animate_this(self.screen, self.AugerBlitStripDict['surface'], (self.AugerBlitStripDict['rect'].width / 5), self.AugerBlitStripDict['rect'].height, (245*self.scalegfx), (115*self.scalegfx), 50)
		self.AugerCoverDict = functions.scaled_image_dict('', '', '', 'gfx/AugerCover.png', self.scalegfx, 266, 114)

		self.TrainingDoorBlitStripDict = functions.scaled_image_dict('', '', '', 'gfx/TrainingDoorsBlitStrip.png', self.scalegfx, 0, 0)
		self.TrainingDoorResearchAnimate = classes.animate_this(self.screen, self.TrainingDoorBlitStripDict['surface'], (self.TrainingDoorBlitStripDict['rect'].width / 8), self.TrainingDoorBlitStripDict['rect'].height, (131*self.scalegfx), (115*self.scalegfx), 50)
		self.TrainingDoorEngineerAnimate = classes.animate_this(self.screen, self.TrainingDoorBlitStripDict['surface'], (self.TrainingDoorBlitStripDict['rect'].width / 8), self.TrainingDoorBlitStripDict['rect'].height, (195*self.scalegfx), (115*self.scalegfx), 50)
		self.TrainingDoorPilotAnimate = classes.animate_this(self.screen, self.TrainingDoorBlitStripDict['surface'], (self.TrainingDoorBlitStripDict['rect'].width / 8), self.TrainingDoorBlitStripDict['rect'].height, (259*self.scalegfx), (115*self.scalegfx), 50)

		self.BayBackGround = []	
		for self.i in range(0, 9):
			self.BayBackGround.append(functions.scaled_image_dict('', '', '', 'gfx/BayBackgroundTile.png', self.scalegfx, (79+(32*self.i)), 63))
		self.ShuttleCrewBays = []
		for self.i in range(0, 4):
			self.ShuttleCrewBays.append(functions.scaled_image_dict(self.shuttlebays[self.i], 'Crew Bay '+''.join(str(self.i +1)), 'bay', 'gfx/CrewBay.png', self.scalegfx, 80, (72+(34*self.i))))
		self.NewShuttleDict = functions.scaled_image_dict('newshuttle', 'New Shuttle', 'newshuttle', 'gfx/NewShuttleIcon.png', self.scalegfx, 84, 19)
		self.RemShuttleDict = functions.scaled_image_dict('remshuttle', 'Dismantle Shuttle', 'remshuttle', 'gfx/NoShipIcon.png', self.scalegfx, 79, 19)
		self.FuelBarDict = functions.scaled_image_dict('', '', '', 'gfx/FuelBar.png', self.scalegfx, 166, 204)
		self.FuelBarNegDict = functions.scaled_image_dict('remfuel', 'Remove Fuel', 'remfuel', 'gfx/fuelneg.png', self.scalegfx, 168, 207)
		self.FuelBarPlusDict = functions.scaled_image_dict('addfuel', 'Add Fuel', 'addfuel', 'gfx/fuelplus.png', self.scalegfx, 240, 207)
		self.CockPitDict = functions.scaled_image_dict('cockpit', 'Cockpit', 'shuttleselect', 'gfx/CockPitSelect.png', self.scalegfx, 114, 22)
		self.Pod1Dict = functions.scaled_image_dict('pod1', 'Pod 1', 'shuttleselect', 'gfx/PodSelect.png', self.scalegfx, 138, 24)
		self.DriveDict = functions.scaled_image_dict('drive', 'Drive', 'shuttleselect', 'gfx/DriveSelect.png', self.scalegfx, 161, 19)
		self.CockPitActiveDict = functions.scaled_image_dict('', '', '', 'gfx/CockPitSelectActive.png', self.scalegfx, 114, 22)
		self.Pod1ActiveDict = functions.scaled_image_dict('', '', '', 'gfx/PodSelectActive.png', self.scalegfx, 138, 24)
		self.DriveActiveDict = functions.scaled_image_dict('', '', '', 'gfx/DriveSelectActive.png', self.scalegfx, 161, 19)

		self.SwitchStoreDict = functions.scaled_image_dict ('switchstore', 'Switch Store', 'switchstore', 'gfx/SwitchStore.png', self.scalegfx, 80, 200)
		self.AddRigDict = functions.scaled_image_dict ('addrig', 'Add Mining Rig', 'addrig', 'gfx/AddMiningRig.png', self.scalegfx, 289, 168) 
		self.NotResearchedDict =  functions.scaled_image_dict ('', '', '', 'gfx/research/notresearched.png', self.scalegfx, 208, 82)


	def regenerateInteractiveIcons(self):
		del self.interactiveIcons [:]
		self.interactiveIcons.append(self.ProductionDict)
		self.interactiveIcons.append(self.TrainingDict)
		self.interactiveIcons.append(self.ResearchDict)
		self.interactiveIcons.append(self.ShuttleBayDict)
		self.interactiveIcons.append(self.MiningDict)
		self.interactiveIcons.append(self.StorageDict)
		if (self.shuttleEnabled):
			self.interactiveIcons.append(self.ShuttleDict)

	def displaymain(self, timepassed):
		self.regenerateInteractiveIcons()
		self.screen.blit(self.EarthCityMainDict['surface'], self.EarthCityMainDict['rect'])
		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/earthcity.ogg'
		return(self.mymusic)

	def displayproduction(self, player, iteminfo, timepassed):
		self.regenerateInteractiveIcons()
		self.productShortageList = False
		del self.prodProgressList[:]
		self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('engineer', self.thisLocation, 'production')
		if (self.crewfound):
			self.screen.blit(self.ProdGreenLightDict['surface'], self.ProdGreenLightDict['rect'])
		else:
			self.ProdRedLightAnimate.update(timepassed)
		self.screen.blit(self.EarthCityProdDict['surface'], self.EarthCityProdDict['rect'])
		self.screen.blit(self.ProdCrewToBayDict['surface'], self.ProdCrewToBayDict['rect'])
		if (self.crewfound):
			self.interactiveIcons.append(self.ProdCrewToBayDict)
			functions.drawText(str(self.leadername), self.font, WHITE, self.screen, (246*self.scalegfx), (186*self.scalegfx))
			functions.drawText(str(self.rank), self.font, WHITE, self.screen, (246*self.scalegfx), (195*self.scalegfx))
			functions.drawText(str(self.numberofcrew), self.font, WHITE, self.screen, (246*self.scalegfx), (205*self.scalegfx))
		else:
			self.leadername = 'None'
			functions.drawText(str(self.leadername), self.font, WHITE, self.screen, (246*self.scalegfx), (186*self.scalegfx))
		self.interactiveIcons.extend(self.prodButtons.display(iteminfo, player.getProdItems(), self.crewfound))
		if (len(self.productionQueue) > 0):
			for self.item in self.productionQueue:
				if (self.item['status'] == 'shortage'):
					self.materials = iteminfo.GetRawMaterials(self.item['item'])
					self.productShortageList = self.RawMaterialsInventory.ShortageList(self.materials)
					functions.drawText('Shortages:', self.font, RED, self.screen, (63*self.scalegfx), (52*self.scalegfx))
					self.yoffset = 0
					self.itemnum = 0
					self.txtseperation = 9 * self.scalegfx
					for self.material in self.productShortageList:
						self.itemnum += 1
						functions.drawText(self.material, self.font, YELLOW, self.screen, (63*self.scalegfx), (52*self.scalegfx+(self.itemnum*self.txtseperation)))
					self.AugerAnimate.stop()
					self.mymusic = 'sound/productionidle.ogg'
				elif (self.item['status'] == 'orbitonly'):
					self.txtseperation = 9 * self.scalegfx
					functions.drawText('Item produced', self.font, YELLOW, self.screen, (63*self.scalegfx), (52*self.scalegfx))
					functions.drawText('in orbit only', self.font, RED, self.screen, (63*self.scalegfx), (52*self.scalegfx+self.txtseperation))
					self.AugerAnimate.stop()
				else:
					self.BookDisplayDict = iteminfo.GetBookItemSurfaces(self.item['item'])
					self.screen.blit(self.BookDisplayDict['surface'], self.BookDisplayDict['rect'])
					self.prodProgressList = iteminfo.GetProgessSurfaceList(self.item['item'])
					if (self.item['remainingbuildtime'] > (self.item['buildtime'] / 2)):
						self.screen.blit(self.prodProgressList[0]['surface'], self.prodProgressList[0]['rect'])
					elif (self.item['remainingbuildtime'] > (self.item['buildtime'] / 3)):
						self.screen.blit(self.prodProgressList[1]['surface'], self.prodProgressList[1]['rect'])
					else:
						self.screen.blit(self.prodProgressList[2]['surface'], self.prodProgressList[2]['rect'])
					self.AugerAnimate.update(timepassed)
					self.mymusic = 'sound/productionactive.ogg'
		else:
			self.screen.blit(self.NoProdDict['surface'], self.NoProdDict['rect'])
			self.AugerAnimate.stop()
			self.mymusic = 'sound/productionidle.ogg'
		self.screen.blit(self.AugerCoverDict['surface'], self.AugerCoverDict['rect'])
		self.alwaysdisplay(timepassed)
		return(self.mymusic)

	def displaytraining(self, player, timepassed):
		self.regenerateInteractiveIcons()
		self.pool, self.trainingresearchers, self.trainingengineers, self.trainingpilots, self.trainingresearch, self.trainingengineer, self.trainingpilot = player.returnTrainingStatus()
		self.screen.blit(self.EarthCityTrainingDict['surface'], self.EarthCityTrainingDict['rect'])
		functions.drawText(str(self.pool), self.font, WHITE, self.screen, (65*self.scalegfx), (125*self.scalegfx))
		if (self.trainingresearch):
			self.TrainingDoorResearchAnimate.update(timepassed, False)

		else:
			self.TrainingDoorResearchAnimate.reverse(timepassed,False)
			if not (self.TrainingDoorResearchAnimate.StillPlaying()):
				functions.drawText(str(self.trainingresearchers), self.font, YELLOW, self.screen, (153*self.scalegfx), (117*self.scalegfx))
				self.LeftResearchDict = {'name': 'rresearchers',
						    	'description': 'Remove Researchers',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((140*self.scalegfx, 152*self.scalegfx), (146*self.scalegfx, 148*self.scalegfx), (146*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.RightResearchDict = {'name': 'aresearchers',
						    	'description': 'Add Researchers',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((162*self.scalegfx, 152*self.scalegfx), (156*self.scalegfx, 148*self.scalegfx), (156*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.interactiveIcons.append(self.LeftResearchDict)
				self.interactiveIcons.append(self.RightResearchDict)

		if (self.trainingengineer):
			self.TrainingDoorEngineerAnimate.update(timepassed, False)
		else:
			self.TrainingDoorEngineerAnimate.reverse(timepassed, False)
			if not (self.TrainingDoorEngineerAnimate.StillPlaying()):
				functions.drawText(str(self.trainingengineers), self.font, DARKBLUE, self.screen, (217*self.scalegfx), (117*self.scalegfx))
				self.LeftEngineerDict = {'name': 'rengineers',
						    	'description': 'Remove Engineers',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((204*self.scalegfx, 152*self.scalegfx), (210*self.scalegfx, 148*self.scalegfx), (210*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.RightEngineerDict = {'name': 'aengineers',
						    	'description': 'Add Engineers',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((226*self.scalegfx, 152*self.scalegfx), (220*self.scalegfx, 148*self.scalegfx), (220*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.interactiveIcons.append(self.LeftEngineerDict)
				self.interactiveIcons.append(self.RightEngineerDict)

		if (self.trainingpilot):
			self.TrainingDoorPilotAnimate.update(timepassed, False)
		else:
			self.TrainingDoorPilotAnimate.reverse(timepassed, False)
			if not (self.TrainingDoorPilotAnimate.StillPlaying()):
				functions.drawText(str(self.trainingpilots), self.font, RED, self.screen, (281*self.scalegfx), (117*self.scalegfx))
				self.LeftPilotDict = {'name': 'rpilots',
						    	'description': 'Remove Marines',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((268*self.scalegfx, 152*self.scalegfx), (274*self.scalegfx, 148*self.scalegfx), (274*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.RightPilotDict = {'name': 'apilots',
						    	'description': 'Add Marines',
							'typeOfimage': 'training',
							'rect': pygame.draw.polygon(self.screen, WHITE, ((290*self.scalegfx, 152*self.scalegfx), (284*self.scalegfx, 148*self.scalegfx), (284*self.scalegfx, 156*self.scalegfx)), 2),
				      			  }
				self.interactiveIcons.append(self.LeftPilotDict)
				self.interactiveIcons.append(self.RightPilotDict)

		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/training.ogg'
		return(self.mymusic)

	def displayresearch(self, player, timepassed, iteminfo):
		self.regenerateInteractiveIcons()
		self.txtseperation = 9.5 * self.scalegfx
		self.itemMass = 0
		self.ResearchItemStatusDict = player.getResearch()
		self.Mats = False
		self.status = False
		self.ResearchItem = False
		self.researchtime = 0
		self.researchtimeRemaining = 0
		self.percentcomplete = 0
		self.screen.blit(self.EarthCityResearchDict['surface'], self.EarthCityResearchDict['rect'])
		self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('researcher', self.thisLocation, 'research')
		if (self.crewfound):
			functions.drawText(str(self.leadername), self.font, WHITE, self.screen, (104*self.scalegfx), (186*self.scalegfx))
			functions.drawText(str(self.rank), self.font, WHITE, self.screen, (104*self.scalegfx), (195*self.scalegfx))
			functions.drawText(str(self.numberofcrew), self.font, WHITE, self.screen, (104*self.scalegfx), (205*self.scalegfx))
		else:
			self.leadername = 'None'
			functions.drawText(str(self.leadername), self.font, WHITE, self.screen, (104*self.scalegfx), (186*self.scalegfx))
		if (len(self.ResearchQueue) > 0):
			for self.ResearchItemDict in self.ResearchQueue:
				self.ResearchItem = self.ResearchItemDict['item']
				self.status = self.ResearchItemDict['status']
				self.researchtime = float(self.ResearchItemDict['researchtime'])
				self.researchtimeRemaining = float(self.ResearchItemDict['remainingresearchtime'])
				break
			if (self.status == 'start'):
				self.interactiveIcons.extend(self.ResearchButtons.displayResearch(iteminfo, self.ResearchItemStatusDict, self.researchSelectedItem, timepassed))
			else:
				self.ResearchButtons.displayResearch(iteminfo, self.ResearchItemStatusDict, self.researchSelectedItem, timepassed)
				functions.drawText('Team Working', self.researchfont, DARKGREEN, self.screen, (82*self.scalegfx), (55*self.scalegfx))
				functions.drawText('Project Is', self.font, WHITE, self.screen, (80*self.scalegfx), (55*self.scalegfx)+self.txtseperation)
				self.percentcomplete = float((1 - (self.researchtimeRemaining / self.researchtime))*100)
				self.message = '%(Done)04.1f %%  Complete' % {"Done": self.percentcomplete}
				functions.drawText(self.message, self.font, WHITE, self.screen, (80*self.scalegfx), (55*self.scalegfx)+(self.txtseperation*2))
			if (self.researchSelectedItem == self.ResearchItem):
				functions.drawText('ITEM ANALYSIS', self.researchfont, RED, self.screen, (58*self.scalegfx), (25*self.scalegfx))
				functions.drawText(iteminfo.GetItemName(self.ResearchItem), self.researchfont, WHITE, self.screen, (58*self.scalegfx), ((25*self.scalegfx) + self.txtseperation))
				functions.drawText('Tech Level', self.researchfont, STORECOLOUR, self.screen, (58*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*2)))
				functions.drawText(iteminfo.GetItemTechLevel(self.ResearchItem), self.researchfont, RED, self.screen, (128*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*2)))
				self.screen.blit(self.NotResearchedDict['surface'], self.NotResearchedDict['rect'])
			else:
				player.setResearchStatus(self.ResearchItem, 'waiting')
				del self.ResearchQueue [:]
		else:
			self.interactiveIcons.extend(self.ResearchButtons.displayResearch(iteminfo, self.ResearchItemStatusDict, self.researchSelectedItem, timepassed))
		if (self.researchSelectedItem):
			if (self.ResearchItemStatusDict[self.researchSelectedItem] == 'done'):
				functions.drawText('ITEM ANALYSIS', self.researchfont, RED, self.screen, (58*self.scalegfx), (25*self.scalegfx))
				functions.drawText(iteminfo.GetItemName(self.researchSelectedItem), self.researchfont, WHITE, self.screen, (58*self.scalegfx), ((25*self.scalegfx) + self.txtseperation))
				functions.drawText('Tech Level', self.researchfont, STORECOLOUR, self.screen, (58*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*2)))
				functions.drawText(iteminfo.GetItemTechLevel(self.researchSelectedItem), self.researchfont, RED, self.screen, (128*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*2)))
				functions.drawText('Mass', self.researchfont, STORECOLOUR, self.screen, (58*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*4)))
				self.itemMass = iteminfo.GetItemMass(self.researchSelectedItem)
				if (self.itemMass >= 1000):
					self.amountadjustpos = 15*self.scalegfx
				elif (self.itemMass >= 100):
					self.amountadjustpos = 11*self.scalegfx
				elif (self.itemMass >= 10):
					self.amountadjustpos = 7*self.scalegfx
				else:
					self.amountadjustpos = 0
				functions.drawText(str(self.itemMass), self.researchfont, RED, self.screen, (98*self.scalegfx) - self.amountadjustpos, ((25*self.scalegfx) + (self.txtseperation*4)))
				functions.drawText('T  .', self.researchfont, STORECOLOUR, self.screen, (110*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*4)))
				self.itemnum = 5
				self.Mats = iteminfo.GetRawMaterials(self.researchSelectedItem)
				for self.material in self.Mats:
					if (int(self.Mats[self.material]) >= 1000):
						self.amountadjustpos = 1.5*self.scalegfx
					elif (int(self.Mats[self.material]) >= 100):
						self.amountadjustpos = 1*self.scalegfx
					elif (int(self.Mats[self.material]) >= 10):
						self.amountadjustpos = 0.5*self.scalegfx
					else:
						self.amountadjustpos = 0
					functions.drawText(self.Mats[self.material], self.font, DARKGREEN, self.screen, (82*self.scalegfx) - self.amountadjustpos, ((25*self.scalegfx) + (self.txtseperation*self.itemnum)))
					functions.drawText(self.material, self.font, DARKGREEN, self.screen, (98*self.scalegfx), ((25*self.scalegfx) + (self.txtseperation*self.itemnum)))
					self.itemnum += 1
				if (iteminfo.ItemBuildable(self.researchSelectedItem)):
					functions.drawText('This item may', self.researchfont, WHITE, self.screen, (58*self.scalegfx), ((145*self.scalegfx)))
					functions.drawText('be produced', self.researchfont, WHITE, self.screen, (60*self.scalegfx), ((145*self.scalegfx) + self.txtseperation ))
					if (iteminfo.OrbitOnly(self.researchSelectedItem)):
						functions.drawText('in ORBIT only', self.researchfont, RED, self.screen, (58*self.scalegfx), ((145*self.scalegfx) + (self.txtseperation*2)))
					else:
						functions.drawText('in any factory', self.researchfont, WHITE, self.screen, (58*self.scalegfx), ((145*self.scalegfx) + (self.txtseperation*2)))
				self.ItemDisplayDict = iteminfo.GetResearchItemSurfaces(self.researchSelectedItem)
				self.screen.blit(self.ItemDisplayDict['surface'], self.ItemDisplayDict['rect'])
		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/research.ogg'
		return(self.mymusic)

	def displayshuttlebay(self, player, timepassed):
		self.regenerateInteractiveIcons()
		for self.tile in self.BayBackGround:
			self.screen.blit(self.tile['surface'], self.tile['rect'])
		if (self.shuttleEnabled):
			self.shuttle.NewShuttle(timepassed)
		else:
			self.shuttle.RemoveShuttle(timepassed)
		if not (self.shuttle.ShuttleDeploying()) and not (self.shuttle.ShuttleUnDeploying()) and (self.shuttleEnabled):
			self.interactiveIcons.extend(self.shuttle.ShuttleManage(timepassed, self.shuttleManage))
		if (self.shuttleManage == 'cockpit') and not (self.shuttle.ShuttleMoving()):
			for self.tile in self.ShuttleCrewBays:
				self.screen.blit(self.tile['surface'], self.tile['rect'])
				self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('pilot', self.thisLocation, self.tile['name'])
				if not (self.crewfound):
					self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('engineer', self.thisLocation, self.tile['name'])
					if not (self.crewfound):
						self.interactiveIcons.append(self.tile)
					else:					
						self.newRect = self.tile['rect'].copy()
						self.newRect.inflate_ip(0, -(self.tile['rect'].height * (0.08*self.scalegfx)))
						self.newRect.move_ip(0, (-2*self.scalegfx))
						self.interactiveIcons.append({'name': self.tile['name'],
								    	'description': 'Send to Production',
									'typeOfimage': 'engtoprod',
									'rect': pygame.draw.rect(self.screen, DARKBLUE, self.newRect, 0),
				      					  })
				else:
					self.newRect = self.tile['rect'].copy()
					self.newRect.inflate_ip(0, -(self.tile['rect'].height * (0.08*self.scalegfx)))
					self.newRect.move_ip(0, (-2*self.scalegfx))
					self.interactiveIcons.append({'name': self.tile['name'],
									'description': 'Send to Ship',
									'typeOfimage': 'pilottoship',
									'rect': pygame.draw.rect(self.screen, RED, self.newRect, 0),
									})
				if (self.crewfound):
					functions.drawText(str(self.rank), self.font, WHITE, self.screen, (self.newRect.x + 1), self.newRect.y)
					functions.drawText(str(self.leadername), self.font, WHITE, self.screen, (self.newRect.x + 1), (self.newRect.y + (10*self.scalegfx)))
					functions.drawText(str(self.numberofcrew), self.font, WHITE, self.screen, (self.newRect.x + (18*self.scalegfx)), (self.newRect.y + (19*self.scalegfx)))
		self.screen.blit(self.EarthCityShuttleBayDict['surface'], self.EarthCityShuttleBayDict['rect'])
		if (self.shuttle.ShuttleDeploying()):
			self.screen.blit(self.NewShuttleDict['surface'], self.NewShuttleDict['rect'])
		elif (self.shuttle.ShuttleUnDeploying()):
			self.screen.blit(self.RemShuttleDict['surface'], self.RemShuttleDict['rect'])
			self.screen.blit(self.FuelBarDict['surface'], self.FuelBarDict['rect'])
			self.screen.blit(self.FuelBarNegDict['surface'], self.FuelBarNegDict['rect'])
			self.screen.blit(self.FuelBarPlusDict['surface'], self.FuelBarPlusDict['rect'])
		elif (self.shuttleEnabled):
			self.screen.blit(self.RemShuttleDict['surface'], self.RemShuttleDict['rect'])
			if (self.shuttleManage == 'cockpit'):
				self.screen.blit(self.CockPitActiveDict['surface'], self.CockPitActiveDict['rect'])
			else:
				self.screen.blit(self.CockPitDict['surface'], self.CockPitDict['rect'])
				self.interactiveIcons.append(self.CockPitDict)
			if (self.shuttleManage == 'pod1'):
				self.screen.blit(self.Pod1ActiveDict['surface'], self.Pod1ActiveDict['rect'])
			else:		
				self.screen.blit(self.Pod1Dict['surface'], self.Pod1Dict['rect'])
				self.interactiveIcons.append(self.Pod1Dict)
			if (self.shuttleManage == 'drive'):
				self.screen.blit(self.DriveActiveDict['surface'], self.DriveActiveDict['rect'])
			else:
				self.screen.blit(self.DriveDict['surface'], self.DriveDict['rect'])
				self.interactiveIcons.append(self.DriveDict)
			self.screen.blit(self.FuelBarDict['surface'], self.FuelBarDict['rect'])
			self.screen.blit(self.FuelBarNegDict['surface'], self.FuelBarNegDict['rect'])
			self.screen.blit(self.FuelBarPlusDict['surface'], self.FuelBarPlusDict['rect'])
			self.interactiveIcons.append(self.RemShuttleDict)
			self.interactiveIcons.append(self.FuelBarNegDict)
			self.interactiveIcons.append(self.FuelBarPlusDict)
		else:
			self.screen.blit(self.NewShuttleDict['surface'], self.NewShuttleDict['rect'])
			self.interactiveIcons.append(self.NewShuttleDict)
		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/spacebay.ogg'
		return(self.mymusic)

	def displaymining(self,timepassed):
		self.regenerateInteractiveIcons()
		self.screen.blit(self.EarthCityMiningDict['surface'], self.EarthCityMiningDict['rect'])
		self.itemnum = 0
		self.txtseperation = 9 * self.scalegfx
		self.mineralsDict = self.RawMaterialsInventory.GetMineralSeam()
		for self.mineral, self.amount in self.mineralsDict.items():
			self.itemnum += 1
			if (self.amount == 0):
				functions.drawText('SURVEY', self.font, DARKGREEN, self.screen, (96*self.scalegfx), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
			else:
				self.amountadjustpos = 2*self.scalegfx
				if (int(self.amount) >= 10000):
					self.amountadjustpos = 19*self.scalegfx
				elif (self.amount >= 1000):
					self.amountadjustpos = 15*self.scalegfx
				elif (self.amount >= 100):
					self.amountadjustpos = 11*self.scalegfx
				elif (self.amount >= 10):
					self.amountadjustpos = 7*self.scalegfx
				functions.drawText(str(self.amount), self.font, WHITE, self.screen, ((126*self.scalegfx)-self.amountadjustpos), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
			pygame.draw.polygon(self.screen, DARKGREEN, ((132*self.scalegfx, (34*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (34*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (32*self.scalegfx+(self.itemnum*self.txtseperation))), (138*self.scalegfx, (35*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (39*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (37*self.scalegfx+(self.itemnum*self.txtseperation))), (132*self.scalegfx, (37*self.scalegfx+(self.itemnum*self.txtseperation)))), 0)
			functions.drawText(self.mineral, self.font, WHITE, self.screen, (140*self.scalegfx), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
		functions.drawText('Rigs', self.font, STORECOLOUR, self.screen, (273*self.scalegfx), (155*self.scalegfx))
		functions.drawText(str(self.derricks), self.font, WHITE, self.screen, (276*self.scalegfx), (173*self.scalegfx))
		self.screen.blit(self.AddRigDict['surface'], self.AddRigDict['rect'])
		self.interactiveIcons.append(self.AddRigDict)
		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/mining.ogg'
		return(self.mymusic)

	def displaystorage(self, iteminfo, timepassed, player):
		self.itemnum = 0
		self.txtseperation = 9 * self.scalegfx
		self.productShortageList = False
		self.selectedmaterials = False
		self.numberCouldbeBuilt = 0
		self.regenerateInteractiveIcons()
		self.screen.blit(self.EarthCityStorageDict['surface'], self.EarthCityStorageDict['rect'])
		self.screen.blit(self.SwitchStoreDict['surface'], self.SwitchStoreDict['rect'])
		self.interactiveIcons.extend(self.StorageButtons.display(iteminfo, player.getProdItems(), False, self.storeSelectedItem, timepassed))
		if (self.storeSelectedItem):
			self.selectedmaterials = iteminfo.GetRawMaterials(self.storeSelectedItem).copy()
			if not (self.RawMaterialsInventory.CheckInventory(self.selectedmaterials)):
				self.productShortageList = self.RawMaterialsInventory.ShortageList(self.selectedmaterials)
			else:
				self.numberCouldbeBuilt = self.RawMaterialsInventory.NumberCouldbeBuilt(self.selectedmaterials)
			if (self.numberCouldbeBuilt >= 10000):
				self.amountadjustpos = 2*self.scalegfx
			elif (self.numberCouldbeBuilt>= 1000):
				self.amountadjustpos = 1.5*self.scalegfx
			elif (self.numberCouldbeBuilt >= 100):
				self.amountadjustpos = 1*self.scalegfx
			elif (self.numberCouldbeBuilt >= 10):
				self.amountadjustpos = 0.5*self.scalegfx
			else:
				self.amountadjustpos = 0
			functions.drawText('Enough', self.font, YELLOW, self.screen, (195*self.scalegfx), (73*self.scalegfx))
			functions.drawText('Supplies', self.font, YELLOW, self.screen, (195*self.scalegfx), ((73*self.scalegfx) + self.txtseperation))
			functions.drawText('For', self.font, YELLOW, self.screen, (195*self.scalegfx), ((73*self.scalegfx) + self.txtseperation * 2))
			functions.drawText(str(self.numberCouldbeBuilt), self.font, YELLOW, self.screen, ((194*self.scalegfx) + self.amountadjustpos), ((73*self.scalegfx) + self.txtseperation * 3))
			functions.drawText(iteminfo.GetItemName(self.storeSelectedItem), self.font, YELLOW, self.screen, (195*self.scalegfx), ((73*self.scalegfx) + self.txtseperation * 4))
		if (self.displayItemInventory):
			self.itemsDict = self.ItemsInventory.GetItems()
			for self.item, self.amount in self.itemsDict.items():
				self.itemnum += 1
				self.amountadjustpos = 2*self.scalegfx
				if (self.amount >= 100):
					self.amountadjustpos = 11*self.scalegfx
				elif (self.amount >= 10):
					self.amountadjustpos = 7*self.scalegfx
				functions.drawText(str(self.amount), self.font, YELLOW, self.screen, ((126*self.scalegfx)-self.amountadjustpos), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
				functions.drawText(iteminfo.GetItemName(self.item), self.font, WHITE, self.screen, (140*self.scalegfx), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
		else:
			self.mineralsDict = self.RawMaterialsInventory.GetMaterials()		
			for self.mineral, self.amount in self.mineralsDict.items():
				self.itemnum += 1
				self.amountadjustpos = 2*self.scalegfx
				if (int(self.amount) >= 10000):
					self.amountadjustpos = 19*self.scalegfx
				elif (int(self.amount) >= 1000):
					self.amountadjustpos = 15*self.scalegfx
				elif (int(self.amount) >= 100):
					self.amountadjustpos = 11*self.scalegfx
				elif (int(self.amount) >= 10):
					self.amountadjustpos = 7*self.scalegfx
				self.numcolour = STORECOLOUR
				if (self.selectedmaterials):
					for self.selectedmat in self.selectedmaterials:
						if (self.selectedmat == self.mineral):
							self.numcolour = GREEN
				if (self.productShortageList):
					for self.shortmineral in self.productShortageList:
						if (self.shortmineral == self.mineral):
							self.numcolour = RED
				functions.drawText(str(self.amount), self.font, self.numcolour, self.screen, ((126*self.scalegfx)-self.amountadjustpos), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
				for self.minedmineral in self.RawMaterials:
					if (self.minedmineral == self.mineral):
						pygame.draw.polygon(self.screen, DARKBLUE, ((132*self.scalegfx, (34*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (34*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (32*self.scalegfx+(self.itemnum*self.txtseperation))), (138*self.scalegfx, (35*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (39*self.scalegfx+(self.itemnum*self.txtseperation))), (134*self.scalegfx, (37*self.scalegfx+(self.itemnum*self.txtseperation))), (132*self.scalegfx, (37*self.scalegfx+(self.itemnum*self.txtseperation)))), 0)
				functions.drawText(self.mineral, self.font, WHITE, self.screen, (140*self.scalegfx), (30*self.scalegfx+(self.itemnum*self.txtseperation)))
		self.interactiveIcons.append(self.SwitchStoreDict)
		self.alwaysdisplay(timepassed)
		self.mymusic = 'sound/storage.ogg'
		return(self.mymusic)

	def toggleStorage(self):
		if (self.displayItemInventory):
			self.displayItemInventory = False
		else:
			self.displayItemInventory = True

	def alwaysdisplay(self, timepassed):
		self.screen.blit(self.EarthCityModulesDict['surface'], self.EarthCityModulesDict['rect'])		
		self.screen.blit(self.ProductionDict['surface'], self.ProductionDict['rect'])
		self.screen.blit(self.TrainingDict['surface'], self.TrainingDict['rect'])
		self.screen.blit(self.ResearchDict['surface'], self.ResearchDict['rect'])
		self.screen.blit(self.ShuttleBayDict['surface'], self.ShuttleBayDict['rect'])
		self.screen.blit(self.MiningDict['surface'], self.MiningDict['rect'])
		self.screen.blit(self.StorageDict['surface'], self.StorageDict['rect'])
		if (self.shuttleEnabled):
			self.screen.blit(self.ShuttleDict['surface'], self.ShuttleDict['rect'])

	def whichscreen(self, subscreen, earthcityscreen, player, iteminfo, timepassed):
		self.requestedmusic = False
		if (subscreen == 'production'):
			self.requestedmusic = earthcityscreen.displayproduction(player, iteminfo, timepassed)
		elif (subscreen == 'training'):
			self.requestedmusic = earthcityscreen.displaytraining(player, timepassed)
		elif (subscreen == 'research'):
			self.requestedmusic = earthcityscreen.displayresearch(player, timepassed, iteminfo)
		elif (subscreen == 'shuttlebay'):
			self.requestedmusic = earthcityscreen.displayshuttlebay(player, timepassed)
		elif (subscreen == 'mining'):
			self.requestedmusic = earthcityscreen.displaymining(timepassed)
		elif (subscreen == 'storage'):
			self.requestedmusic = earthcityscreen.displaystorage(iteminfo, timepassed, player)
		else:
			self.requestedmusic = earthcityscreen.displaymain(timepassed)
		return(self.requestedmusic)

	def myicons(self):
		return(self.interactiveIcons)

	def enableshuttle(self):
		self.shuttle = True

	def disableshuttle(self):
		self.shuttle = False

	def DoMining(self):
		self.RawMaterialsInventory.DoMining(self.derricks)

	def DoProduction(self, player, iteminfo):
		if (self.mehfuel):
			self.RawMaterialsInventory.MakeMeh()
		for self.item in self.productionQueue:
			self.materials = iteminfo.GetRawMaterials(self.item)
			if (self.item['status'] == 'shortage'):
				if (self.RawMaterialsInventory.CheckInventory(self.materials)):
					self.item['status'] = 'good'
			if (self.item['status'] == 'good') or (self.item['status'] == 'start'):
				self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('engineer', self.thisLocation, 'production')
				if (self.crewfound):
					if (self.item['status'] == 'start'):
						self.RawMaterialsInventory.removeMineral(self.materials)				
						self.item['status'] = 'good'
					self.item['remainingbuildtime'] -= 1
					self.crew.taskdone()
					if (self.item['remainingbuildtime'] <= 0):
						self.ItemsInventory.AddItems(self.item['item'])
						self.productionQueue.remove(self.item)

	def addProduction(self, item, iteminfo, player, dialogbox):
		self.inQueue = False
		self.buildtime = False
		self.materials = False
		self.status = False
		self.addToQueue = False
		self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('engineer', self.thisLocation, 'production')
		if not (self.crewfound):
			dialogbox.setDialog('Train some engineers first')
		else:
			for self.prodItemDict in self.productionQueue:
				if (item == self.prodItemDict['item']):
					self.inQueue = True
					break
			if not (self.inQueue):
				for self.prodItemDict in self.productionQueue:
					self.status = self.prodItemDict['status']
					break
				if (self.status == 'start') or (self.status == 'shortage') or (self.status == 'orbitonly'):
					del self.productionQueue [:]
				if (len(self.productionQueue) < 1):
					self.materials = iteminfo.GetRawMaterials(item)
					if (iteminfo.OrbitOnly(item)):
						self.status = 'orbitonly'
					elif (self.RawMaterialsInventory.CheckInventory(self.materials)):
						self.status = 'start'
					else:
						self.status = 'shortage'
					self.buildtime = iteminfo.GetBuildTime(item)
					if (self.rank == 'Apprentice'):
						self.buildtime += 18
					elif (self.rank == 'Engineer'):
						self.buildtime += 6
					if (self.numberofcrew < 110):
						self.buildtime += self.buildtime*2
					self.productionQueue.append({ 'item': item,
									'buildtime': int(self.buildtime),
									'remainingbuildtime': int(self.buildtime),
									'status': self.status
									})
				else:
					dialogbox.setDialog('Already Producing')

	def AddRig(self):
		if not (self.derricks >= MAXDERRICK):
			if (self.ItemsInventory.DeployRig()):
				self.derricks += 1

	def SetStoreSelectedItem(self, item):
		self.storeSelectedItem = item

	def SetResearchSelectedItem(self, item):
		self.researchSelectedItem = item

	def DoResearch(self, player, iteminfo):
		for self.ResearchItemDict in self.ResearchQueue:
			if (self.ResearchItemDict['remainingresearchtime'] > 0):
				self.ResearchItemDict['status'] = 'inprogress'
				self.ResearchItemDict['remainingresearchtime'] -= 1
			else:
				player.setResearchStatus(self.ResearchItemDict['item'], 'done')
				if (iteminfo.ItemBuildable(self.ResearchItemDict['item'])):
					player.addProdItem(self.ResearchItemDict['item'])
					self.ItemsInventory.AddNewItem(self.ResearchItemDict['item'])
					if (self.ResearchItemDict['item'] == 'schassis'):
						player.addResearch('toolpod')
						player.addResearch('supplypod')
						player.addResearch('cryopod')
						player.addResearch('offrame')
				elif (self.ResearchItemDict['item'] == 'mehfuel'):
					self.mehfuel = True
					self.RawMaterialsInventory.addNewMineral('MeH')
				elif (self.ResearchItemDict['item'] == 'hedfuel'):
					self.RawMaterialsInventory.addNewMineral('HeD')
				self.ResearchQueue.remove(self.ResearchItemDict)
			break

	def AddResearch(self, item, iteminfo, player, dialogbox):
		self.status = False
		self.previousItem = False
		self.crewfound, self.crew, self.leadername, self.rank, self.numberofcrew = player.crewSearch('researcher', self.thisLocation, 'research')
		if not (self.crewfound):
			dialogbox.setDialog('Train some researchers first')
		else:
			for self.ResearchItemDict in self.ResearchQueue:
				self.previousItem = self.ResearchItemDict['item']
				self.status = self.ResearchItemDict['status']
				break
			if (self.status == 'start'):
				player.setResearchStatus(self.previousItem, 'waiting')
				del self.ResearchQueue [:]
			if (len(self.ResearchQueue) < 1):
				player.setResearchStatus(item, 'inprogress')
				self.researchtime = iteminfo.GetResearchTime(item)
				if (self.numberofcrew < 110):
					self.researchtime += self.researchtime*2
				self.ResearchQueue.append({ 'item': item,
							'researchtime': int(self.researchtime),
							'remainingresearchtime': int(self.researchtime),
							'status': 'start'
							})
			else:
				dialogbox.setDialog('Already Researching')

	def NewShuttle(self, dialogbox):
		if not (self.shuttleEnabled):
			if (self.ItemsInventory.DeployItem('schassis')):
				self.shuttleEnabled = True
			else:
				dialogbox.setDialog('None Available')

	def RemoveShuttle(self):
		self.ItemsInventory.RetrieveItem('schassis')
		self.shuttleEnabled = False
		
	def ManageShuttle(self, manage):
		self.shuttleManage = manage

	def doTick(self, player, iteminfo):
		self.DoMining()
		self.DoProduction(player, iteminfo)
		self.DoResearch(player, iteminfo)


